<template>

  <div class="textEditor">
    <div class="text-header">
      <el-input v-model="param.title" maxlength="20" placeholder="请输入标题"></el-input>
      <el-button size="small" type="primary" @click="printEditorHtml">发布</el-button>
    </div>
    <!-- 工具栏 -->
    <Toolbar
        class="Toolbar"
        style="width: 100vw; border-bottom: 1px solid #ccc"
        :editorId="editorId"
        :defaultConfig="toolbarConfig"
        :mode="mode"
    />
    <div class="content">
    <Editor
        class="editor"
        style="overflow-y: hidden;"
        :editorId="editorId"
        :defaultConfig="editorConfig"
        :defaultHtml="defaultHtml"
        :mode="mode"
        @onChange="onChange"
    />
    </div>
  </div>
</template>

<script>
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar, getEditor, removeEditor } from '@wangeditor/editor-for-vue'
import {postArticle} from "@/api/article/article"
import {mapState} from "vuex";
export default {
  components: { Editor, Toolbar },

  data() {
    return {
      editorId: `w-e-${Math.random().toString().slice(-5)}`, //【注意】编辑器 id ，要全局唯一
      toolbarConfig: {},
      editorConfig: { placeholder: '请输入内容...' },
      mode: 'simple', // or 'simple'
      defaultHtml: '',
      latestContent:[],

      param:{
        title:'',
        summary:'',
        body:'',
        userName:'',
      }
    }
  },
  computed: {
    ...mapState({
      userInf: 'userInf'
    }),
  },
  methods: {
    onChange(editor) {
      this.latestContent = editor.children
    },
    printEditorHtml() {
      const editor = getEditor(this.editorId)
      if (editor == null) return
      this.param.body=editor.getHtml()
      this.param.summary=this.latestContent[0].children[0].text
      this.param.userName=this.userInf.uname
      this.$openLoading()
      postArticle(this.param).then(res=>{
        if(res.data.meta.code===200){
          this.$openLoading().close()
          this.$router.push('/')
        }
      })
    }
  },
  beforeDestroy() {
    const editor = getEditor(this.editorId)
    if (editor == null) return

    // 【注意】组件销毁时，及时销毁编辑器
    editor.destroy()
    removeEditor(this.editorId)
  }

}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="scss" scoped>
  .textEditor{
    .text-header{
      display: flex;
      justify-content: space-between;
    }
    .content{
      width: 100vw;
      height: calc(100% - 40px);
      .editor{
        width: 50%;
      }
      .textShow{
        width: 50%;
      }
    }
  }
</style>
